// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Defines the content script for test_extension.  The
 * test_extension is a Chrome Extension that tests the Chrome Extension API is
 * working as expected.  The extension is loaded in Chrome and then compared to
 * the Mimic wrapped version for non-Chrome browsers to ensure that they
 * produce the same results.
 *
 * The content script is expected to be paired with a specific html file with
 * corresponding html.
 *
 * @author jasonstredwick@google.com (Jason Stredwick)
 */


/**
 * Calls the initialization for all the tests managed by this extension.
 */
function init() {
  initComm();
  initConn();
  initBrowserActions();
  initWindows();
  initGeneral();
  initXSS();
}


/**
 * Initializes the browser action tests elements.
 */
function initBrowserActions() {
  var badgeText = document.getElementById('ba-badge-text');
  var badgeColor = document.getElementById('ba-badge-color');
  var title = document.getElementById('ba-title');
  var icon = document.getElementById('ba-icon');

  var badgeTextButton = document.getElementById('ba-badge-text-button');
  var badgeColorButton = document.getElementById('ba-badge-color-button');
  var titleButton = document.getElementById('ba-title-button');
  var iconButton = document.getElementById('ba-icon-button');

  // Expected results: throw exception.
  try {
    chrome.browserAction.setBadgeText('new title from jason');
    console.error('ERROR: Was able to change browser action title from ' +
                  'content script.');
  } catch (error) {}

  badgeTextButton.addEventListener('click', function() {
    chrome.extension.sendRequest({'msg': 'browserAction',
                                  'type': 'badgeText',
                                  'value': badgeText.value});
  }, false);
  badgeColorButton.addEventListener('click', function() {
    chrome.extension.sendRequest({'msg': 'browserAction',
                                  'type': 'badgeColor',
                                  'value': badgeColor.value});
  }, false);
  titleButton.addEventListener('click', function() {
    chrome.extension.sendRequest({'msg': 'browserAction',
                                  'type': 'title',
                                  'value': title.value});
  }, false);
}


/**
 * Initializes the communication (chrome.extension.sendRequest) tests elements.
 */

function initComm() {
  var ping = document.getElementById('comm-ping');
  var received = document.getElementById('comm-received');
  var sendInput = document.getElementById('comm-send');
  var sendButton = document.getElementById('comm-send-button');

  sendInput.value = 'SendValue1';

  try {
    ping.addEventListener('click', function() {
      chrome.extension.sendRequest({'msg': 'ping'});
    }, false);

    chrome.extension.onRequest.addListener(function(req, sender, resp) {
      if (!req) {
        received.value = 'No request.';
      } else {
        received.value = req['msg'] || 'No message.';
      }
    });

    sendButton.addEventListener('click', function() {
      chrome.extension.sendRequest({'msg': sendInput.value}, function(data) {
        if (data && data['respMsg']) {
          received.value = 'Response: ' + data['respMsg'];
        }
      });
    }, false);
  } catch (error) {
    console.log('ERROR: Caught exception in init comm: ' + error);
  }
}


/**
 * Initializes the communication (chrome.extension.connect) tests elements.
 */
function initConn() {
  var ping = document.getElementById('conn-ping');
  var received = document.getElementById('conn-received');
  var sendInput = document.getElementById('conn-send');
  var sendButton = document.getElementById('conn-send-button');

  sendInput.value = 'SendValue1';

  try {
    var port = chrome.extension.connect({'name': 'test content script'});
    if (!port) {
      console.error('ERROR: Failed to create connection with background.');
      return;
    }

    ping.addEventListener('click', function() {
      port.postMessage({'msg': 'ping'});
    }, false);

    port.onMessage.addListener(function(req) {
      if (!req) {
        received.value = 'No request.';
      } else {
        received.value = req['msg'] || 'No message.';
      }
    });

    sendButton.addEventListener('click', function() {
      port.postMessage({'msg': sendInput.value});
    }, false);
  } catch (error) {
    console.log('ERROR: Caught exception in init conn: ' + error);
  }
}


/**
 * Initializes the window tests elements.
 */
function initWindows() {
  //var features = document.getElementById('window-features');
  var left = document.getElementById('window-left');
  var top = document.getElementById('window-top');
  var width = document.getElementById('window-width');
  var height = document.getElementById('window-height');
  var create = document.getElementById('window-create');
  var createButton = document.getElementById('window-create-button');
  var winObj = document.getElementById('window-object');
  var typeNormal = document.getElementById('window-normal');
  var typePopup = document.getElementById('window-popup');

  //features.value = '';
  create.value = 'http://www.jasonstredwick.net';
  left.value = 100;
  top.value = 100;
  width.value = 600;
  height.value = 600;
  typeNormal.setAttribute('checked', true);
  typePopup.removeAttribute('checked');

  createButton.addEventListener('click', function() {
    var type = 'normal';
    if (typePopup.checked) {
      type = 'popup';
    }

    chrome.extension.sendRequest({
      'msg': 'windowCreate',
      'value': {
        //'features': features.value,
        'type': type,
        'url': create.value,
        'left': (isNaN(parseInt(left.value)) || parseInt(left.value) < 0) ? 0 :
            parseInt(left.value),
        'top': (isNaN(parseInt(top.value)) || parseInt(top.value) < 0) ? 0 :
            parseInt(top.value),
        'width': ((isNaN(parseInt(width.value)) || parseInt(width.value) < 400)
            ? 400 : parseInt(width.value)),
        'height':
            ((isNaN(parseInt(height.value)) || parseInt(height.value) < 400) ?
                400 : parseInt(height.value))
      }}, function(data) {
        if (data) {
          winObj.innerHTML = JSON.stringify(data);
        }
      });
  }, false);
}


/**
 * Initializes the general tests elements.  This include
 * chrome.extension.getURL.
 */
function initGeneral() {
  var baseText = document.getElementById('get-url-base-text');
  var url1Text = document.getElementById('get-url-1-text');
  var url2Text = document.getElementById('get-url-2-text');

  var baseButton = document.getElementById('get-url-base-button');
  var url1Button = document.getElementById('get-url-1-button');
  var url2Button = document.getElementById('get-url-2-button');

  var msgBase = {'msg': 'url', 'url': 'base'};
  baseButton.addEventListener('click', function() {
    chrome.extension.sendRequest(msgBase, function(data) {
      if (data && data['respMsg']) {
        baseText.innerHTML = 'Base Chrome URL is: ' + data['respMsg'];
      }
    });
  }, false);

  var msg1 = {'msg': 'url', 'url': 'url1'};
  url1Button.addEventListener('click', function() {
    chrome.extension.sendRequest(msg1, function(data) {
      if (data && data['respMsg']) {
        url1Text.innerHTML = 'Chrome URL /path/file1.html is: ' +
                             data['respMsg'];
      }
    });
  }, false);

  var msg2 = {'msg': 'url', 'url': 'url2'};
  url2Button.addEventListener('click', function() {
    chrome.extension.sendRequest(msg2, function(data) {
      if (data && data['respMsg']) {
        url2Text.innerHTML = 'Chrome URL path/file2.html is: ' +
                             data['respMsg'];
      }
    });
  }, false);
}


/**
 * Initializes the XSS tests elements.
 */
function initXSS() {
  var csXSSSameText = document.getElementById('xss-cs-same-text');
  var csXSSChromeText = document.getElementById('xss-cs-chrome-text');
  var csXSSServerText = document.getElementById('xss-cs-server-text');

  var csXSSSameButton = document.getElementById('xss-cs-same-button');
  var csXSSChromeButton = document.getElementById('xss-cs-chrome-button');
  var csXSSServerButton = document.getElementById('xss-cs-server-button');

  var baseUrl = chrome.extension.getURL('');

  csXSSSameButton.addEventListener('click', function() {
    csXSSSameText.innerHTML = requestFile(
        'http://TEST_SERVER/~jasonstredwick/xss_file1.txt');
  }, false);
  csXSSChromeButton.addEventListener('click', function() {
    csXSSChromeText.innerHTML =
        requestFile(baseUrl + 'data/xss_file2.txt');
  }, false);
  csXSSServerButton.addEventListener('click', function() {
    csXSSServerText.innerHTML =
        requestFile('http://KNOWN_EXTERNAL_SERVER/layer/simple/get');
  }, false);

  var bgXSSSameText = document.getElementById('xss-bg-same-text');
  var bgXSSChromeText = document.getElementById('xss-bg-chrome-text');
  var bgXSSServerText = document.getElementById('xss-bg-server-text');

  var bgXSSSameButton = document.getElementById('xss-bg-same-button');
  var bgXSSChromeButton = document.getElementById('xss-bg-chrome-button');
  var bgXSSServerButton = document.getElementById('xss-bg-server-button');

  var msgSame = {
    'msg': 'xss',
    'url': 'http://TEST_SERVER/~jasonstredwick/xss_file1.txt'};
  bgXSSSameButton.addEventListener('click', function() {
    chrome.extension.sendRequest(msgSame, function(data) {
      if (data && data['respMsg']) {
        bgXSSSameText.innerHTML = data['respMsg'];
      }
    });
  }, false);
  var msgChrome = {
    'msg': 'xss',
    'url': baseUrl + 'data/xss_file2.txt'};
  bgXSSChromeButton.addEventListener('click', function() {
    chrome.extension.sendRequest(msgChrome, function(data) {
      if (data && data['respMsg']) {
        bgXSSChromeText.innerHTML = data['respMsg'];
      }
    });
  }, false);
  var msgServer = {
    'msg': 'xss',
    'url': 'https://KNOWN_EXTERNAL_SERVER/layer/simple/get'};
  bgXSSServerButton.addEventListener('click', function() {
    chrome.extension.sendRequest(msgServer, function(data) {
      if (data && data['respMsg']) {
        bgXSSServerText.innerHTML = data['respMsg'];
      }
    });
  }, false);
}


/**
 * Requests a file specified by the url and using an XMLHttpRequest.
 */
function requestFile(url) {
  try {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, false);
    xhr.send();
  } catch (error) {
    return 'Failed to send request.';
  }

  if (xhr.status != 200) {
    return 'Request failed with status: ' + xhr.status;
  }

  return xhr.responseText;
}


/**
 * Call the init function to initialize the html page and begin the test.
 */
init();

